class StackTraceUtils{
  /// 基础偏移量, 相当于dart代码的偏移量
  static int? baseIsolateInstructions;
  static int? baseVmInstructions;


  /// 解析类似于这样的堆栈信息，需要把真实地址解析出来，并且进行校验
  /// 目标： 搜索 isolate_instructions 的取值，这是指令集的整体的初始位置
  /// 通过下方 #0x abs 真实地址 与 偏移地址 进行校验, _kDartIsolateSnapshotInstructions地址 = 真实地址 - 偏移地址
  ///
  /// Warning: This VM has been configured to produce stack traces that violate the Dart standard.
  /// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
  /// pid: 31521, tid: 31567, name 1.ui
  /// build_id: '07cc131c2a169d987595fbb60170e55e'
  /// isolate_dso_base: 786f8eb000, vm_dso_base: 786f8eb000
  /// isolate_instructions: 786f9cfaa0, vm_instructions: 786f9cb000
  ///     #00 abs 000000786fac305f virt 00000000001d805f _kDartIsolateSnapshotInstructions+0xf35bf  ->  786F9CFAA0
  ///     #01 abs 000000786fa9cc6f virt 00000000001b1c6f _kDartIsolateSnapshotInstructions+0xcd1cf  ->  786F9CFAA0
  ///     #02 abs 000000786fa9d70b virt 00000000001b270b _kDartIsolateSnapshotInstructions+0xcdc6b  ->  786F9CFAA0
  ///
  static String transformStackTraceAnsSave(String stackStr) {
    String outSt = "";
    int line = 1;
    int lineLimit = 10;
    var isolateInstructions = "";
    int? tempIsolateInstructions;
    var baseUnCorrectCount = 0;
    var splitList = stackStr.split("\n");
    for (String str in splitList) {
      bool shouldContinue = false;
      if (str.contains("pid: ") && str.contains("tid: ")) {
        /// 程序执行的进程以及线程
        var lineStrs = str.split(", ");
        for (String lineStr in lineStrs) {
          if (lineStr.contains("pid:") || lineStr.contains("tid:")) {
            var valueStr = lineStr.split(": ");
            if (valueStr.isNotEmpty) {
              outSt += ", ${valueStr.first} is ${valueStr.last}";
            }
          } else {
            outSt += ", other line: $lineStr\n";
          }
        }
        // outSt += str + "\n";
      } else if (str.contains("isolate_dso_base: ") &&
          str.contains("vm_dso_base: ")) {
        /// Dart 虚拟机中与动态共享对象（DSO，Dynamic Shared Object）相关的基地址
        var lineStrs = str.split(", ");
        for (String lineStr in lineStrs) {
          if (lineStr.contains("isolate_dso_base:") ||
              lineStr.contains("vm_dso_base:")) {
            var valueStr = lineStr.split(": ");
            if (valueStr.isNotEmpty) {
              outSt += ", ${valueStr.first} is ${valueStr.last}";
            }
          } else {
            outSt += ", other line: $lineStr \n";
          }
        }
        // outSt += str + "\n";
      } else if (str.contains("isolate_instructions: ") &&
          str.contains("vm_instructions: ")) {
        /// 具备内存地址和指令
        var lineStrs = str.split(", ");
        for (String lineStr in lineStrs) {
          if (lineStr.contains("isolate_instructions:") ||
              lineStr.contains("vm_instructions:")) {
            var valueStr = lineStr.split(": ");
            if (valueStr.isNotEmpty) {
              if (valueStr.first == "isolate_instructions") {
                isolateInstructions = valueStr.last;
                baseIsolateInstructions = _hexToInt(valueStr.last);
              } else if (valueStr.first == "vm_instructions") {
                baseVmInstructions = _hexToInt(valueStr.last);
              }
              outSt += ", ${valueStr.first} is ${valueStr.last}";
            }
          } else {
            outSt += ", other line: $lineStr";
          }
        }
        // outSt += str + "\n";
      } else if ((str.contains("abs") || str.contains("virt")) &&
          str.contains("_kDartIsolateSnapshotInstructions")) {
        /// 具备真实地址的判断
        if (str.contains("abs") && str.contains("virt")) {
          /// 替换开头内容
          var lineStrs = str.replaceAll("    #", "#").split(" ");
          if (lineStrs.length >= 6) {
            var actualAbs = lineStrs[2];
            var dartBaseAndOffsets = lineStrs[5].split("+");
            var offset = dartBaseAndOffsets.last;
            var countBase =
                int.tryParse(_hexSubtraction(actualAbs, offset), radix: 16);
            var isSameToIsolateInstructions =
                countBase == int.tryParse(isolateInstructions, radix: 16);

            /// 做数值校验
            if (countBase != null) {
              if (!isSameToIsolateInstructions) {
                baseUnCorrectCount++;
              }
              tempIsolateInstructions = countBase;
            }

            outSt +=
                "$str, count base: ${countBase?.toRadixString(16)}, is same to isolateInstructions: $isSameToIsolateInstructions\n";
          }
        } else if (str.contains("abs")) {
          var lineStrs = str.replaceAll("    #", "#").split(" ");
          if (lineStrs.length >= 4) {
            var actualAbs = lineStrs[2];
            var dartBaseAndOffsets = lineStrs[3].split("+");
            var offset = dartBaseAndOffsets.last;
            var countBase =
                int.tryParse(_hexSubtraction(actualAbs, offset), radix: 16);
            var isSameToIsolateInstructions =
                countBase == int.tryParse(isolateInstructions, radix: 16);
            outSt = outSt +
                "$str, count base: ${countBase?.toRadixString(16)}, is same to isolateInstructions: $isSameToIsolateInstructions\n";
          }
        } else {
          /// 仅仅虚拟地址无法计算，应该认为是异常情况
        }
        // outSt += str + "\n";
      } else {
        shouldContinue = true;
      }

      if (baseUnCorrectCount > 0) {
        baseIsolateInstructions = tempIsolateInstructions;
      }

      if (line++ > lineLimit) {
        return "baseIsolateInstructions -------> ${baseIsolateInstructions?.toRadixString(16)} \n $outSt";
      }
      if (shouldContinue) {
        continue;
      }
    }
    return "baseIsolateInstructions -------> ${baseIsolateInstructions?.toRadixString(16)} \n $outSt";
  }

  static int? _hexToInt(String hex) {
    if (hex.toUpperCase().contains("0X")) {
      return int.tryParse(hex.substring(2), radix: 16);
    } else {
      return int.tryParse(hex, radix: 16);
    }
  }

  static String _hexSubtraction(String hex1, String hex2) {
    var hex1Int = _hexToInt(hex1);
    var hex2Int = _hexToInt(hex2);
    if (hex1Int != null && hex2Int != null) {
      return (hex1Int - hex2Int).toRadixString(16);
    }
    return "";
  }
}